package org.example.bighomework.TC;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/TC")
public class TCController {
    @Autowired
    private TCService tcService;
    //主页
    @GetMapping("/")
    public String viewHomePage(Model model){
        return findPaginated(1, "Tno", "asc", model);
    }
    //增加
    @GetMapping("/showTCForm")
    public String showTCForm(Model model) {
        TC tc = new TC();
        model.addAttribute("tc", tc);
        return "new_TC";
    }
    //保存和更新
    @PostMapping("/saveTC")
    public String saveTC(@ModelAttribute("tc") TC tc) {
        tcService.saveTC(tc);
        return "redirect:/TC/";
    }

    @GetMapping("/showFormForUpdate/{Tno}/{Cno}")
    public String showFormForUpdate(@PathVariable(value = "Tno") String Tno,@PathVariable(value = "Cno") String Cno, Model model) {
        TnoCnoPK tnoCnoPK=new TnoCnoPK(Tno,Cno);
        TC tc = tcService.getTCById(tnoCnoPK);
        model.addAttribute("tc", tc);
        return "update_TC";
    }
    //删除
    @GetMapping("/deleteTC/{Tno}/{Cno}")
    public String deleteTC(@PathVariable(value = "Tno") String Tno,@PathVariable(value = "Cno") String Cno) {
        TnoCnoPK tnoCnoPK=new TnoCnoPK(Tno,Cno);
        this.tcService.deleteTCById(tnoCnoPK);
        return "redirect:/TC/";
    }
    //按教师编号查询
    @GetMapping("/query{Tno}")
    public String query(@PathVariable(value = "Tno") String Tno, Model model) {
        List<TC> listTC = tcService.findByTno(Tno);
        model.addAttribute("listTC", listTC);
        return "TCIndex";
    }
    //获取分页数据
    @GetMapping("/page/{pageNo}")
    public String findPaginated(@PathVariable(value = "pageNo") int pageNo,
                                @RequestParam("sortField") String sortField,
                                @RequestParam("sortDir") String sortDir,
                                Model model) {
        int pageSize = 3;

        Page<TC> page = tcService.findPaginated(pageNo, pageSize, sortField, sortDir);
        List<TC> listTC = page.getContent();

        model.addAttribute("currentPage", pageNo);
        model.addAttribute("totalPages", page.getTotalPages());
        model.addAttribute("totalItems", page.getTotalElements());
        model.addAttribute("sortField", sortField);
        model.addAttribute("sortDir", sortDir);
        model.addAttribute("reverseSortDir", sortDir.equals("asc") ? "desc" : "asc");
        model.addAttribute("listTC", listTC);
        return "TCIndex";
    }
}
